package com.fishbone.cloud.auth.security.service;

import com.fishbone.cloud.auth.constants.FishBoneConstant;
import com.fishbone.cloud.auth.exception.FishBoneAuthException;
import com.fishbone.cloud.auth.security.model.FishBoneUser;
import com.fishbone.cloud.user.api.bo.UserBO;
import com.fishbone.cloud.user.api.feign.IUserClient;
import com.fishbone.common.utils.Func;
import com.fishbone.common.utils.WebUtil;
import com.fishbone.core.api.ResponseEntity;
import com.fishbone.core.api.ResultCode;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * @ClassName FishBoneUserDetailsServiceImpl
 * @Author huyaxi
 * @DATE 2020/3/31 9:50
 */
@Service
@AllArgsConstructor
public class FishBoneUserDetailsServiceImpl implements UserDetailsService {

    private final IUserClient userClient;

    @SneakyThrows
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        String tenant = Objects.requireNonNull(WebUtil.getRequest()).getParameter(FishBoneConstant.TENANT);
        if(StringUtils.isEmpty(tenant)){
            throw new FishBoneAuthException(ResultCode.PARAM_MISS);
        }
        ResponseEntity<UserBO> entity = userClient.getUserAuth(tenant,username);
        if(ResultCode.INTERNAL_SERVER_ERROR.getCode() == entity.getCode()){
            throw new FishBoneAuthException(ResultCode.INTERNAL_SERVER_ERROR);
        }
        UserBO userBO = userClient.getUserAuth(tenant, username).getData();
        if(Func.isEmpty(userBO)){
            throw new FishBoneAuthException(ResultCode.LOGIN_ERROR);
        }
        return new FishBoneUser(userBO.getAccount(),userBO.getPassword(),!userBO.getIsDeleted(),true,
                true,true,AuthorityUtils.commaSeparatedStringToAuthorityList(Func.join(userBO.getRoleIds())),
                userBO.getId(),userBO.getAccount(),userBO.getName(),userBO.getAvatar(),userBO.getTenantId(),userBO.getPhone(), userBO.getRoleIds(),
                userBO.getStatus(),userBO.getIsDeleted());
    }
}
